import { BASE_URL } from "../../utils/config";

interface Course {
  id: string
  courseName: string
}

interface IPageData {
  date: string
  startDate: string
  endDate: string
  courseIndex: number
  courses: Course[]
  reason: string
  images: string[]
}

Page<IPageData>({
  data: {
    date: '',
    startDate: '',
    endDate: '',
    courseIndex: -1,
    courses: [],
    reason: '',
    images: []
  },

  onLoad() {
    // 设置日期范围
    const today = new Date()
    const startDate = today.toISOString().split('T')[0]
    const endDate = new Date(today.setMonth(today.getMonth() + 1)).toISOString().split('T')[0]
    
    this.setData({
      date: startDate, // 设置默认日期为今天
      startDate,
      endDate
    })
    // 获取课程列表
    this.fetchCourseList()
  },

  onDateChange(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      date: e.detail.value
    })

    // 获取课程列表
    this.fetchCourseList()
  },

  onCourseChange(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      courseIndex: parseInt(e.detail.value)
    })
  },

  onReasonInput(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      reason: e.detail.value
    })
  },

  async chooseImage() {
    try {
      const res = await wx.chooseMedia({
        count: 3 - this.data.images.length,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed']
      })

      const newImages = res.tempFiles.map(file => file.tempFilePath)
      this.setData({
        images: [...this.data.images, ...newImages]
      })
    } catch (error) {
      wx.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  },

  deleteImage(e: WechatMiniprogram.CustomEvent) {
    const index = e.currentTarget.dataset.index
    const images = [...this.data.images]
    images.splice(index, 1)
    this.setData({ images })
  },

  previewImage(e: WechatMiniprogram.CustomEvent) {
    const url = e.currentTarget.dataset.url
    wx.previewImage({
      current: url,
      urls: this.data.images
    })
  },

  fetchCourseList() {
    const token = wx.getStorageSync('token')
    wx.request({
      url: `${BASE_URL}/course/leaveList`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
        leaveDate: this.data.date
      },
      success: (res: any) => {
        const { data } = res.data
        if (data) {
          this.setData({
            courses: data
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取课程列表失败',
          icon: 'error'
        })
      }
    })
  },

  async submitForm() {
    const { date, courseIndex, courses, reason, images } = this.data

    if (!date) {
      return wx.showToast({
        title: '请选择请假时间',
        icon: 'none'
      })
    }

    if (courseIndex === -1) {
      return wx.showToast({
        title: '请选择请假课程',
        icon: 'none'
      })
    }

    if (!reason.trim()) {
      return wx.showToast({
        title: '请输入请假理由',
        icon: 'none'
      })
    }

    if (images.length === 0) {
      return wx.showToast({
        title: '请上传请假证明照片',
        icon: 'none'
      })
    }

    wx.showLoading({ title: '提交中' })

    try {
      // 上传图片获取URL
      const token = wx.getStorageSync('token')
      const uploadPromises = images.map(imagePath => {
        return new Promise((resolve, reject) => {
          wx.uploadFile({
            url: `${BASE_URL}/file/upload`,
            filePath: imagePath,
            name: 'file',
            header: {
              'Authorization': `Bearer ${token}`
            },
            success: (res) => {
              const data = JSON.parse(res.data)
              resolve(data.data.url)
            },
            fail: (err) => {
              reject(err)
            }
          })
        })
      })

      const imageUrls = await Promise.all(uploadPromises)

      // 提交请假申请
      await new Promise((resolve, reject) => {
        wx.request({
          url: `${BASE_URL}/check/leaveSave`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: {
            checkDate: date,
            courseId: courses[courseIndex].id,
            reason: reason,
            leaveImage: imageUrls.join(';')
          },
          success: (res: any) => {
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        })
      })

      wx.hideLoading()
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      })
      
      // 返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)

    } catch (error) {
      wx.hideLoading()
      wx.showToast({
        title: '提交失败',
        icon: 'error'
      })
      console.error('提交请假申请失败:', error)
    }
  }
});